package com.small.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

/**
 * 作者: fenny
 * 邮箱: 893146555@qq.com
 * 时间: 2017/10/19 10:56
 * 描述: 通过ApplicationContext获得spring容器中的对象
 */
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext CONTEXT = null;

    private SpringUtil() {
        super();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CONTEXT = applicationContext;
    }

    /**
     * @param beanName b
     * @return 根据名称获取bean
     */
    public static Object getBean(String beanName) {
        return CONTEXT.getBean(beanName);
    }

    /**
     * 根据bean名称获取指定类型bean
     *
     * @param beanName bean名称
     * @param clazz    返回的bean类型,若类型不匹配,将抛出异常
     */
    public static <T> T getBean(String beanName, Class<T> clazz) {
        return CONTEXT.getBean(beanName, clazz);
    }

    /**
     * @param clazz c
     * @return 根据类型获取bean
     */
    public static <T> T getBean(Class<T> clazz) {
        T t = null;
        Map<String, T> map = CONTEXT.getBeansOfType(clazz);
        for (Map.Entry<String, T> entry : map.entrySet()) {
            t = entry.getValue();
        }
        return t;
    }

    /**
     * @param beanName b
     * @return 是否包含bean
     */
    public static boolean containsBean(String beanName) {
        return CONTEXT.containsBean(beanName);
    }

    /**
     * @param beanName b
     * @return 是否是单例
     */
    public static boolean isSingleton(String beanName) {
        return CONTEXT.isSingleton(beanName);
    }

    /**
     * @param beanName b
     * @return bean的类型
     */
    public static Class getType(String beanName) {
        return CONTEXT.getType(beanName);
    }

    public static ApplicationContext getContext() {
        return CONTEXT;
    }
}
